package com.luying.controller.controller;

import com.luying.pojo.*;
import com.luying.service.AuthService;
import com.luying.utils.jedis.JedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by Longjie Bao on 2018/3/12.
 */
@Controller
@RequestMapping("/auth")
public class AuthController {
    private Logger logger = LoggerFactory.getLogger(AuthController.class);
    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Login user) {
        try {
            String account = user.getAccount();
            String password = user.getPassword();
            logger.info("用户{}正在登录",account);
            MenuList login = authService.login(account, password);
            List<Menu> menuList = login.getMenuList();
            if(menuList!=null&&menuList.size()>0){
                return Result.ok(login);
            }
            return Result.loginFailure("用户名或密码错误");
        } catch (Exception e) {
            logger.error("用户登录失败",e);
            return Result.error("用户登录失败");
        }
    }
    @GetMapping("/me")
    @ResponseBody
    public Result getMe(@RequestParam(name="id") Integer id) {
        return Result.ok(authService.getMe(id));
    }

    @GetMapping("/logout")
    @ResponseBody
    public Result logout(@RequestParam(name="id") Integer id) {
        Map<String, Object> login = authService.logout(id);
        return Result.ok();
    }
    @PostMapping("/changePassword")
    @ResponseBody
    public Result changePassword(@RequestBody ChangePassword changePassword) {
        try {
            authService.changePassword(changePassword);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    @GetMapping("/resetPassword")
    @ResponseBody
    public Result resetPassword(@RequestParam(name="account")String account) {
        try {
            authService.resetPassword(account);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
